package com.ys.web.yinsheng.util;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;


/**
 * 
 * <P>BASE64编码解码工具包 </p> <p> 依赖javabase64-1.3.1.jar </P>
 * 
 * @version 1.0
 * @author 黄雄星（13077862552） 2014-1-16 上午8:44:44
 */
public class Base64Utils {

	/**
	 * <p> BASE64字符串解码为二进制数据 </p>
	 * 
	 * @param base64
	 * @return
	 * @throws Exception
	 */
	public static byte[] decode(String base64)  {
		return DatatypeConverter.parseBase64Binary(base64);
	}

	/**
	 * <p> 二进制数据编码为BASE64字符串 </p>
	 * 
	 * @param bytes
	 * @return
	 * @throws Exception
	 */
	public static String encode(byte[] bytes) {
		return DatatypeConverter.printBase64Binary(bytes);
	}

	public static String encodedString(String filePath){
		return Base64.getEncoder().encodeToString(filePath.getBytes());
	}
	public static String decodedString(String encodedString){
		byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
		return new String(decodedBytes);
	}

	public static String getImageBase(String src) throws Exception {

		URL url = new URL(src);
		InputStream in = null;
		byte[] data = null;
		try {
			in = url.openStream();//远程文件
			data = new byte[in.available()];
			in.read(data);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(in!=null)
				in.close();
		}
		return Base64.getEncoder().encodeToString(data);
	}
}
